package com.raymond.redis;


import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 将redis放入spring容器中
 *
 * @author :  raymond
 * @version :  1.0
 * @date :  2019/7/17
 */
@Configuration
@Slf4j
public class RedisHostsConfig {
    private final RedisProperties redisProperties;

    public RedisHostsConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    /**
     * 获取JedisCluster链接
     * @return JedisCluster
     */
    @Bean
    public JedisCluster redisCluster(){
        List<String> serverArray = redisProperties.getCluster().getNodes();
        try{
            //获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)

            Set<HostAndPort> nodes = new HashSet<>();

            for (String ipPort : serverArray) {
                String[] ipPortPair = ipPort.split(":");
                nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.parseInt(ipPortPair[1].trim())));
            }
            JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle());
            jedisPoolConfig.setMaxWaitMillis(5);
            //需要密码连接的创建对象方式
            JedisCluster jedisCluster = new JedisCluster(nodes,redisProperties.getTimeout().getNano(),10000,1,redisProperties.getPassword() ,jedisPoolConfig);
            log.info("获取JedisCluster连接成功{}", serverArray);
            return jedisCluster;
        }catch(Exception e){
            log.error("获取JedisCluster连接异常{}", serverArray, e);
            return null;
        }
    }

}
